require("dotenv").config();
const passport = require("passport");
const {Strategy, ExtractJwt} = require("passport-jwt");
const {BusinessError} = require("../common/util/error");
const {find} = require("../services/user");
const {JWT_SECRET} = process.env;
const strategy = new Strategy(
    {
        jwtFromRequest:ExtractJwt.fromAuthHeaderAsBearerToken(),
        secretOrKey:JWT_SECRET,
    },
    async (jwtPayload,done)=>{
        try{
            const user = await find({id:jwtPayload.id});
            if (!user){
                throw new BusinessError("User not found");
            }
            done(null,user);
        }catch (e){
            done(e);
        }
    }
);
passport.use(strategy);
const initialize = ()=>{
    return passport.initialize();
};
const authenticate = ()=>{
    return passport.authenticate("jwt",{session:false});
};
module.exports = {
    initialize,
    authenticate
};